package com.java.netty.nio.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @Author: Dgg
 * @Date: 2022/1/24 22:08
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtoCol> {
	private int count;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, MessageProtoCol msg) throws Exception {
		//接收数据并且处理
		int len = msg.getLen();
		byte[] bytes = msg.getBytes();

		System.out.println("服务器接收信息如下：");
		System.out.println("长度：" + len);
		System.out.println("内容：" + new String(bytes, CharsetUtil.UTF_8));

		System.out.println("服务器接收到消息数量：" + ++this.count);

		//回复消息
		String s = UUID.randomUUID().toString();
		int length = s.getBytes(CharsetUtil.UTF_8).length;
		byte[] responseContext = s.getBytes(CharsetUtil.UTF_8);
		//构建一个协议包
		MessageProtoCol messageProtoCol = new MessageProtoCol();
		messageProtoCol.setLen(length);
		messageProtoCol.setBytes(responseContext);

		ctx.writeAndFlush(messageProtoCol);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}


}
